package kitwee.com.kanpad;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;

import com.kitwee.serialport.data.model.SerialPortParam;

import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.kitwee.serialport.util.SimpleCountDownTimer;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Base64FromApache;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.bean.KanpadRecyleAdapter;
import kitwee.com.kanpad.bean.SocketEvent;
import kitwee.com.kanpad.bean.SocketPortData;
import kitwee.com.kanpad.bean.TaskListBean;
import kitwee.com.kanpad.orderDetail.OrderDetailActivity;
import kitwee.com.kanpad.orderDetail.SerialPortActivity;
import kitwee.com.kanpad.orderDetail.SerialPortHelper;
import kitwee.com.kanpad.orderDetail.SerialPortPreferences;
import kitwee.com.kanpad.orderDetail.ServerSocetReporter;
import kitwee.com.kanpad.service.PushService;
import okhttp3.Call;
import utils.DeviceUtils;
import utils.FlavorHelper;
import utils.OnMultipleClickListener;
import utils.SPUtils;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements KanpadRecyleAdapter.OnItemClickLitener, ServiceConnection {
    View main;
    String userName;
    String pwd;
    @BindView(R.id.rl_container)
    RecyclerView rlContainer;
    @BindView(R.id.bt_refresh)
    Button btRefresh;
    @BindView(R.id.bt_login_out)
    Button btLoginOut;
    @BindView(R.id.text_kanban_id)
    TextView textKanbanId;
    @BindView(R.id.tv_pre_page)
    TextView tvPrePage;
    @BindView(R.id.tv_next_page)
    TextView tvNextPage;
    @BindView(R.id.progress)
    ProgressBar progress;

    private Handler sHandler;
    private EditText bt_pass;
    private String what;


    private DisplayMetrics displayMetrics;
    private int widthPix;
    private int heightPix;
    private String padid;
    private KanpadRecyleAdapter adapter;
    private int total;
    private String endpoint;
    private String timeSpa;


    @SuppressLint({"InflateParams", "SetJavaScriptEnabled"})
    @Override
    public void onCreate(Bundle savedInstanceState) {

        getPadId();
        MyMultiDexApplication.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        timeSpa = SerialPortPreferences.getTimeSpa();
        sHandler = new Handler();
        sHandler.post(mHideRunnable); // hide the navigation bar
        View decorView = getWindow().getDecorView();
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                sHandler.post(mHideRunnable); // hide the navigation bar
            }
        });
        Intent intent = new Intent(this, PushService.class);
        startService(intent);
        bindService(intent, this, BIND_AUTO_CREATE);

        hideBottomUIMenu();
        //计算平板的分辨率
        calculateResolution();
        getLayoutInflater();
        main = LayoutInflater.from(this).inflate(R.layout.activity_new_main_layout, null);
        main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        setContentView(main);
        ButterKnife.bind(this);
        //获取设备ID
        String yunPaiId = DeviceUtils.getPadionId();
        textKanbanId.setText(yunPaiId);
        textKanbanId.setOnClickListener(new OnMultipleClickListener(3) {
            @Override
            public void onMultipleClick(View v) {
                SerialPortActivity.start(MainActivity.this);
            }
        });
        userName = SPUtils.getString(this, "user");
        pwd = SPUtils.getString(this, "pwd");
        if ((!"".equals(userName)) && (!"".equals(pwd))) {
            userName = new String(Base64FromApache.decodeBase64(userName));
            pwd = new String(Base64FromApache.decodeBase64(pwd));
        } else {
        }
        initView();
        ServerSocetReporter.getInstance().initialize(this);
        if (!TextUtils.isEmpty(timeSpa)) {
            initTimer();
        }
    }

    private void initTimer() {
        mDataTimeout = new SimpleCountDownTimer(Integer.valueOf(timeSpa) * 1000) {
            @Override
            public void onTick(long l) {
                super.onTick(l);
            }

            @Override
            public void onFinish() {
                mDataTimeout.cancel();
                if (socketPortData.size() > 0) {
                    ServerSocetReporter.getInstance().reportRealTimeData(false, socketPortData);
                    socketPortData.clear();
                }
                mDataTimeout.start();
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    protected void onResume() {
        super.onResume();
        progress.setVisibility(View.GONE);
        mlist.clear();
        MobclickAgent.onResume(this);
//        initData(1);
        TaskListBean.RowsBean rosbean = new TaskListBean.RowsBean();
        rosbean.setDevice_name("测试添加");
        rosbean.setClass_name_value("测试添加");
        mlist.add(rosbean);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (progress != null) {
            progress.setVisibility(View.GONE);
            hideBottomUIMenu();
            ServerSocetReporter.getInstance().deinitialize();
        }
    }

    /**
     * 计算平板的分辨率
     */
    private void calculateResolution() {
        displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        widthPix = displayMetrics.widthPixels;
        heightPix = displayMetrics.heightPixels;

    }

    private void getPadId() {
        Intent intent = getIntent();
        padid = intent.getStringExtra("PADID");
    }

    List<TaskListBean.RowsBean> mlist;

    private void initView() {
        mlist = new ArrayList<>();
        final LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        rlContainer.setLayoutManager(mLinearLayoutManager);
        adapter = new KanpadRecyleAdapter(this, mlist);
        rlContainer.setAdapter(adapter);
        adapter.setOnItemClickLitener(this);
    }

    private void initData(final int page) {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        endpoint = BuildConfig.API_ENDPOINT;
        OkHttpUtils.get()
                .tag(this)
//                .url(BuildConfig.API_ENDPOINT + "/productionTask/getProductionTaskList")
                .url(endpoint + "/productionTask/getProductionTaskList")
                .addParams("EQ_kanban_no", textKanbanId.getText().toString())
                .addParams("pun", user)
                .addParams("page", String.valueOf(page))
                .addParams("rows", "999")
                .addParams("pd", digest)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("请求列表失败 ： " + call + "; e ：" + e + " ; id ：" + id);
                        progress.setVisibility(View.GONE);
                        btRefresh.setClickable(true);
                        mlist.clear();
                        ToastUtils.showShort("网络请求超时,请刷新重试!");
                        TaskListBean.RowsBean rosbean = new TaskListBean.RowsBean();
                        rosbean.setDevice_name("测试添加");
                        rosbean.setClass_name_value("测试添加");
                        mlist.add(rosbean);
                        adapter.notifyDataSetChanged();
                        // TODO: 2019/3/4  自动暂停
                        setSerialPortPaused(true);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObj = JSON.parseObject(response);
                        total = Integer.parseInt(jsonObj.getString("total"));
                        if (total >= 0) {
                            JSONArray result = jsonObj.getJSONArray("rows");
                            List<TaskListBean.RowsBean> rowsBeen = JSON.parseArray(result.toString(), TaskListBean.RowsBean.class);
                            mlist.clear();
                            mlist.addAll(rowsBeen);

                            adapter.notifyDataSetChanged();
                            progress.setVisibility(View.GONE);
                            btRefresh.setClickable(true);
                            checkTaskStatus();
                        } else {
                            ToastUtils.showShort("当前机台没有任务");
                            progress.setVisibility(View.GONE);
                            btRefresh.setClickable(true);
                            setSerialPortPaused(true);
                        }
                    }
                });
//        }
    }

    /**
     * 检查任务状态
     */
    private void checkTaskStatus() {
        for (TaskListBean.RowsBean task : mlist) {
            // 实际判断第1个任务应该就可以
            if (!"not_started".equals(task.getTask_status_key())) {
                setSerialPortPaused(false);
                OrderDetailActivity.start(this, task);
                return;
            }
            // 所有任务状态都是"未生产"
            setSerialPortPaused(true);
        }
    }

    /**
     * 预判是否暂停
     *
     * @param paused 是否暂停
     */
    private void setSerialPortPaused(boolean paused) {
        if (paused) {
            confirmSerialPortPaused();
        } else {
            setSerialPortPausedReally(false);
        }
    }

    private void confirmSerialPortPaused() {
        String user = SPUtils.getString(this, "user");
        String key = SPUtils.getString(this, "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        endpoint = BuildConfig.API_ENDPOINT;
        OkHttpUtils.get().url(endpoint + "/userEquipment/getDeviceCollectPermission")
                .addParams("EQ_kanban_no", textKanbanId.getText().toString())
//                .addParams("EQ_kanban_no", "bcf6113f09cd7ff6")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        printApiError("确认暂停出错：" + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject json = JSON.parseObject(response);
                        if (json.getBoolean("status")) {
                            int data = json.getInteger("data");
                            setSerialPortPausedReally(data == 0);
                        } else {
                            printApiError(json.getString("statusCode") + ", " + json.getString("message"));
                        }
                    }
                });
    }

    private void printApiError(String msg) {
        if (BuildConfig.DEBUG) {
            LogUtils.e(msg);
        }
    }

    /**
     * 发送暂停指令
     *
     * @param paused 是否暂停
     */
    private void setSerialPortPausedReally(boolean paused) {
        SerialPortHelper.getInstance(MainActivity.this).setPaused(paused);
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }


    public boolean onTouch(View v, MotionEvent event) {
        int i = v.getSystemUiVisibility();
        if (i == View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) {
            main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        } else if (i == View.SYSTEM_UI_FLAG_VISIBLE) {
            main.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
        return false;
    }

    Runnable mHideRunnable = new Runnable() {
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void run() {
            int flags;
            int curApiVersion = Build.VERSION.SDK_INT;
            if (curApiVersion >= Build.VERSION_CODES.KITKAT) {
                flags =
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_IMMERSIVE
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                ;

            } else {
                flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }
            getWindow().getDecorView().setSystemUiVisibility(flags);
        }
    };


    @Override
    public void onItemClick(View view, int position) {
        if (mlist.size() > 0) {
            TaskListBean.RowsBean rowsBean = mlist.get(position);
            if (FlavorHelper.isGuanWang()) {
                OrderDetailActivity.start(this, rowsBean);
            } else {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.putExtra("id", "1000");
                bundle.putSerializable("rowsBean", rowsBean);
                intent.setClass(MainActivity.this, ListDeatailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }

    }

    @Override
    public void onItemLongClick(View view, int position) {
        LogUtils.e("长按了任务 ： ");
    }

    @OnClick({R.id.tv_pre_page, R.id.tv_next_page, R.id.bt_refresh, R.id.bt_login_out})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_refresh:
                if (mlist.size() > 0) {
                    mlist.clear();
                    rlContainer.removeAllViews();
                    adapter.notifyDataSetChanged();
                    progress.setVisibility(View.VISIBLE);
                    btRefresh.setClickable(false);
                    initData(1);
                } else {
                    initData(1);
                }
                break;
            case R.id.bt_login_out:
                break;
        }
    }


    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        PushService.PushBinder binder = (PushService.PushBinder) iBinder;
        PushService myService = binder.getPushService();
        myService.registerCallBack(new PushService.SocketCallBack() {
            @Override
            public void onDataChanged(Map<String, Map<String, Integer>> returnMap) {
                Message msg = new Message();
                msg.obj = returnMap;
                handler.sendMessage(msg);
            }
        });
    }

    private String currentTypes;

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }

    private CountDownTimer mDataTimeout;

    Map<String, Integer> newMap = new LinkedHashMap<>();
    Map<String, Integer> sheetMap = new LinkedHashMap<>();
    Map<String, Integer> meterMap = new LinkedHashMap<>();
    Map<String, Integer> speedMap = new LinkedHashMap<>();
    private List<SocketPortData> socketPortData = new ArrayList<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Map<String, Map<String, Integer>> returnMap = (Map<String, Map<String, Integer>>) msg.obj;

            if (returnMap.get("sheet") != null) {
                sheetMap.clear();
                sheetMap.putAll(returnMap.get("sheet"));
            }

            if (returnMap.get("meter") != null) {
                meterMap.clear();
                meterMap.putAll(returnMap.get("meter"));
            }
//            Map<String, Integer> sheetMap = returnMap.get("sheet");
//            Map<String, Integer> meterMap = returnMap.get("meter");
            if (returnMap.get("speed") != null) {
                speedMap.clear();
                speedMap.putAll(returnMap.get("speed"));
            }
//            Map<String, Integer> speedMap = returnMap.get("speed");
            if (sheetMap.size() > 0) {
                newMap.put("张/实时产量", sheetMap.get("OUTPUT1"));
                socketPortData.add(new SocketPortData("实时产量", sheetMap.get("OUTPUT1") + "", "张"));
                newMap.put("张/目标产量设定", sheetMap.get("OUTPUT2"));
                socketPortData.add(new SocketPortData("目标产量设定", sheetMap.get("OUTPUT2") + "", "张"));
                newMap.put("张/累计产量设定", sheetMap.get("OUTPUT3"));
                socketPortData.add(new SocketPortData("累计产量设定", sheetMap.get("OUTPUT3") + "", "张"));

            }
            if (meterMap.size() > 0) {
                newMap.put("米/实时产量", meterMap.get("OUTPUT1"));
                socketPortData.add(new SocketPortData("实时产量", meterMap.get("OUTPUT1") + "", "张"));
                newMap.put("米/目标产量设定", meterMap.get("OUTPUT2"));
                socketPortData.add(new SocketPortData("目标产量设定", meterMap.get("OUTPUT2") + "", "张"));

                newMap.put("米/累计产量设定", meterMap.get("OUTPUT3"));
                socketPortData.add(new SocketPortData("累计产量设定", meterMap.get("OUTPUT3") + "", "张"));

            }

            if (speedMap.size() > 0) {
                newMap.put("米/速度", speedMap.get("SPEED"));
                socketPortData.add(new SocketPortData("速度", speedMap.get("SPEED") + "", "米"));
            }
            if (newMap.size() == 7) {
                EventBus.getDefault().postSticky(new SocketEvent(newMap));

                newMap.clear();
                if (mDataTimeout != null) {
                    mDataTimeout.start();
                }

            }
        }
    };


}
